import pyperclip


class UnitProcessor:
    """按单元处理文本，保留或删除指定行"""

    def __init__(self, n: int, x: int, action: str = 'keep'):
        """
        n: 每个处理单元的行数
        x: 每个单元中操作的行号（从1开始）
        action: 'keep' 保留第 x 行, 'delete' 删除第 x 行
        """
        if n <= 0 or x <= 0:
            raise ValueError("行数 n 和 x 必须为正整数")
        if action.lower() not in ('keep', 'delete'):
            raise ValueError("操作类型必须为 'keep' 或 'delete'")
        self.n = n
        self.x = x
        self.action = action.lower()

    def process_lines(self, input_data) -> str:
        """按单元处理多行文本，支持字符串和列表输入"""
        # 统一转换为行列表
        if isinstance(input_data, str):
            lines = input_data.splitlines()
        elif isinstance(input_data, list):
            lines = input_data
        else:
            raise ValueError("输入必须是字符串或字符串列表")

        result_lines = []

        for i in range(0, len(lines), self.n):
            unit = lines[i:i + self.n]
            if 1 <= self.x <= len(unit):
                if self.action == 'keep':
                    result_lines.append(unit[self.x - 1])
                elif self.action == 'delete':
                    del unit[self.x - 1]
                    result_lines.extend(unit)
            else:
                result_lines.extend(unit)  # x超出范围，保留原单元

        # 返回字符串
        return '\n'.join(result_lines)


    @staticmethod
    def read_input(end_marker="end") -> list[str]:
        """从控制台读取多行文本"""
        print(f"请输入多行文本（以 '{end_marker}' 单独一行结束）：")
        lines = []
        while True:
            line = input()
            if line.strip().lower() == end_marker:
                break
            lines.append(line)
        return lines

    def process_and_copy(self, lines: list[str]) -> str:
        """处理文本并复制到剪贴板"""
        processed_lines = self.process_lines(lines)
        result = '\n'.join(processed_lines)

        return result


if __name__ == "__main__":
    while True:
        cont = input("继续？输入 1 继续，2 结束：").strip()
        if cont == '2':
            break

        lines = UnitProcessor.read_input()
        try:
            n = int(input("每个单元的行数 n："))
            x = int(input("要处理的第 x 行（从1开始）："))
            action = input("操作类型（keep: 保留第 x 行，delete: 删除第 x 行）：").strip().lower()
        except Exception as e:
            print("输入错误:", e)
            continue

        processor = UnitProcessor(n=n, x=x, action=action)
        final_text = processor.process_and_copy(lines)
        print("\n处理完成，结果已复制到剪贴板：\n")
        print(final_text)
